import Socket from '@/libs/socket'

export default class WakeUp {
  worker: Socket | null = null

  constructor(options) {
    this.init(options)
  }

  init(options) {
    this.worker = new Socket(import.meta.env.XMOV_APP_WAKEUP_SERVER_URL, {
      onOpen: () => {
        this.log('opened')
        this.worker.send('start')
      },
      onMessage: (e) => {
        this.log(e)
        if (e.data === 'awake') { // 此时语音唤醒成功
          options.onWakeUp()
        }
      },
      onError: (e) => {
        this.log(e)
        if (options?.onError) options?.onError(e)
        this.worker.destroy()
      },
      onClose: () => {
        this.log('close')
        if (options?.onClose) options?.onClose()
      }
    })
  }
  send(data) {
    this.worker?.send(data)
  }
  close() {
    this.worker.destroy()
    this.worker = null
  }
  log(msg) {
    // console.log(':::[wakeup]', msg, new Date())
  }
}